'use strict';

/**
 * Created by zhu on 14/12/21.
 */
angular.module('blog').controller('BlogListCtrl', [
    '$scope',
    '$routeParams',
    '$rootScope',
    '$sce',
    'BlogListService',
    'BlogListByCategoryService',
    'PageConstant',
    'PathSuffixConstant',
    'BlogDetailService',
    'BlogRecycleManageService',
    function ($scope, $routeParams, $rootScope, $sce, BlogListService, BlogListByCategoryService, PageConstant, PathSuffixConstant, BlogDetailService, BlogRecycleManageService) {
        $rootScope.visitedUserId = $routeParams.userId;

        $scope.query = function (pageNumber) {
            $scope.categoryId = $routeParams.categoryId;

            var queryCondition = {
                offset: (pageNumber - 1) * PageConstant.countPerPage,
                countPerPage: PageConstant.countPerPage
            };

            if ($scope.categoryId) {
                queryCondition.categoryId = $scope.categoryId + PathSuffixConstant;
                BlogListByCategoryService.query(queryCondition, function (response) {
                    results(response);
                });
            } else {
                queryCondition.author = $scope.visitedUserId + PathSuffixConstant;
                BlogListService.query(queryCondition, function (response) {
                    results(response);
                });
            }
        };

        $scope.safeHtml = function (blog) {
            if (blog) {
                return $sce.trustAsHtml(blog.content);
            }
        };

        $scope.remove = function (blog) {
            if (confirm('是否删除\"' + blog.title + '\"?')) {
                BlogRecycleManageService.add({identity: blog._id}, function () {
                    $rootScope.deletedBlogId = blog._id;
                    $scope.query(1);
                });
            }
        };

        function results(response) {
            if ($rootScope.deletedBlogId) {// 处理删除
                $scope.blogs = [];
                angular.forEach(response.results, function (v) {
                    if (v._id != $rootScope.deletedBlogId) {
                        $scope.blogs.push(v);
                    }
                });
                $rootScope.deletedBlogId = null;
            } else {
                $scope.blogs = response.results;
            }
            $scope.totalCount = response.totalCount;
        }

        $scope.query(1);

    }]);

